/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package course.services;

import course.entities.User;
import course.providers.jpa.UserGroupProvider;
import course.providers.jpa.UserProvider;
import java.security.Principal;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

/**
 *
 * @author def
 */
public abstract class AUserService {

    @EJB
    protected UserProvider userProvider;

    @EJB
    protected UserGroupProvider groupProvider;

    public User getCurrentUser() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        Principal principal = context.getUserPrincipal();
        String userName = principal.getName();
        return userProvider.findByUserName(userName);
    }

    public String getCurrentUserRole() {
        //TODO: place your code here
        return new String();
    }

    public String logout() {
        try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            String userName = context.getUserPrincipal().getName();
            addInfoMessage("User " + userName + " has been logged out");
            context.invalidateSession();
            return "/welcome.xhtml?faces-redirect=true";
        } catch (Exception ex) {
            return "";
        }
    }

    public void addInfoMessage(String summary) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public void addErrorMessage(String summary) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}
